﻿using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContractorTimesheet.Models;
using ContractorTimesheet.Repository;
using ContractorTimesheet.DataModel;
using ContractorTimesheet.Infrastructure;
using System.Web.Security;
using System.Text;
using SimpleCrypto;

namespace ContractorTimesheet.Controllers
{
    public class HomeController : BaseController
    {
        private UserRepository userRepository = new UserRepository();
        private HolidayRepository holidayRepository = new HolidayRepository();
        private LeaveRepository leaveRepository = new LeaveRepository();
        private const string dayFormat = "00";

        public ActionResult Index()
        {
            MonthlyReportModel model = new MonthlyReportModel();
            IList<Holiday> holidays = holidayRepository.GetHolidays(DateTime.Now.Month);

            int noOfWorkingDays = Calendar.CurrentMonthBusinessDays;
            int noOfActualWorkingDays = noOfWorkingDays - holidays.Count;

            model.Month = DateTime.Today.ToString("MMMM yyyy");
            model.NoOfWorkingDays = noOfWorkingDays.ToString(dayFormat);
            model.NoOfPublicHolidays = holidays.Count.ToString(dayFormat);
            model.PublicHolidays = GetPublicHolidays(holidays);
            model.NoOfActualWorkingDays = noOfActualWorkingDays.ToString(dayFormat);
            model.ContractorLeaves.AddRange(GetContractorLeaves(noOfActualWorkingDays));

            return View(model);
        }

        public ActionResult Login()
        {
            return View();
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();

            CurrentSession.User = null;

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult Authenticate(string username, string password, bool rememberMe)
        {
            User user = userRepository.Validate(username, password);

            LoginStatus status = new LoginStatus();

            if (user == null)
            {
                status.Success = false;
                status.Message = "Invalid UserID or Password!";
                status.TargetURL = Url.Action("Login", "Home");
            }
            else
            {
                FormsAuthentication.SetAuthCookie(user.Username, rememberMe);
                CurrentSession.User = user;
                status.Success = true;
                status.Message = "Login attempt successful!";
                status.TargetURL = (user.IsAdmin) ? Url.Action("Index", "Holidays") : Url.Action("Index", "Leaves");
            }

            return Json(status);
        }

        private string GetleavesTaken(IList<Leave> leaves)
        {
            if (leaves.Count == 0)
                return string.Empty;

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < leaves.Count; i++)
            {
                Leave leave = leaves[i];
                builder.Append(string.Format("{0}", int.Parse(leave.Day).ToOrdinal()));
                if (i != leaves.Count - 1)
                    builder.Append(", ");
            }

            return "(" + builder.ToString() + ")";
        }

        private string GetPublicHolidays(IList<Holiday> holidays)
        {
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < holidays.Count; i++)
            {
                Holiday holiday = holidays[i];
                builder.Append(string.Format("{0} - {1}", int.Parse(holiday.Day).ToOrdinal(), holiday.Description));
                if (i != holidays.Count - 1)
                    builder.Append(", ");
            }

            return builder.ToString();
        }

        private IList<ContractorLeave> GetContractorLeaves(int noOfActualWorkingDays)
        {
            IList<ContractorLeave> contractorLeaves = new List<ContractorLeave>();

            foreach (User user in userRepository.GetAllActiveUsers())
            {
                IList<Leave> leaves = leaveRepository.GetLeaves(user.Id, DateTime.Now.Month, DateTime.Now.Year);

                ContractorLeave item = new ContractorLeave
                {
                    BadgeNo = user.BadgeNo,
                    ResourceName = string.Format("{0}, {1}", user.Lastname, user.Firstname),
                    PO = user.PO,
                    NoOfLeavesTaken = leaves.Count.ToString(dayFormat),
                    LeavesTaken = GetleavesTaken(leaves),
                    DaysWorked = (noOfActualWorkingDays - leaves.Count).ToString(dayFormat)
                };

                contractorLeaves.Add(item);
            }

            return contractorLeaves;
        }



    }



}